package com.fulihui.wgj.config;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.apache.http.Header;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * RestTemplate 配置
 *
 * @author wang_wx
 * @date 2018-08-02
 */
@Configuration
public class RestTemplateConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(RestTemplateConfig.class);

    /**
     * 构造restful client
     *
     * @return restful client
     */
    @Bean
    public RestTemplate restTemplate() {
        // 添加内容转换器
        List<HttpMessageConverter<? extends Object>> messageConverters = new ArrayList<>();

        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        messageConverters.add(new FormHttpMessageConverter());
        messageConverters.add(new MappingJackson2HttpMessageConverter());
        messageConverters.add(new FastJsonHttpMessageConverter());
        RestTemplate restTemplate = new RestTemplate(messageConverters);
        restTemplate.setRequestFactory(clientHttpRequestFactory());
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
        LOGGER.info("初始化restTemplate完成");
        return restTemplate;
    }

    /**
     * 构造http请求工厂
     *
     * @return http请求工厂
     */
    public ClientHttpRequestFactory clientHttpRequestFactory() {
        try {
            // 长连接保持20秒,如有其它请求可以复用该链接
            PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager(20, TimeUnit.SECONDS);
            // 总连接数
            pollingConnectionManager.setMaxTotal(1000);
            // 同路由的并发数
            pollingConnectionManager.setDefaultMaxPerRoute(1000);
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            httpClientBuilder.setConnectionManager(pollingConnectionManager);
            // 重试次数，默认是3次，没有开启
//        httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true));
            httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());
            List<Header> headers = new ArrayList<>();
            headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));
            headers.add(new BasicHeader("Connection", "Keep-Alive"));
            httpClientBuilder.setDefaultHeaders(headers);
            HttpClient httpClient = httpClientBuilder.build();
            // httpClient连接配置，底层是配置RequestConfig
            HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
            // 连接超时
            clientHttpRequestFactory.setConnectTimeout(15000);
            // 数据读取超时时间，即SocketTimeout
            clientHttpRequestFactory.setReadTimeout(5000);
            // 连接不够用的等待时间，不宜过长，必须设置，比如连接不够用时，时间过长将是灾难性的
            clientHttpRequestFactory.setConnectionRequestTimeout(3000);
            // 缓冲请求数据，默认值是true。通过POST或者PUT大量发送数据时，建议将此属性更改为false，以免耗尽内存。
            clientHttpRequestFactory.setBufferRequestBody(false);
            return clientHttpRequestFactory;
        } catch (Exception e) {
            LOGGER.error("初始化连接池异常！{}", e);
        }
        return null;
    }

}